using IStrong.EC.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using IStrong.EC.ExtensionMethods;
using IStrong.EC.WebApi.Results.Repository;
using IStrong.EC.WebApi.Results.Entity;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Hosting;

namespace IStrong.EC.WebApi.Results.Controllers
{
    /// <summary>
    /// Api控制器模板
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    public class MaintenanceController : BaseController
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<MaintenanceController> _logger;

        /// <summary>
        /// 配置
        /// </summary>
        private readonly IConfiguration _config;

        /// <summary>
        /// 服务合同
        /// </summary>
        private readonly Maintenance _maintenance;

        /// <summary>
        /// 
        /// </summary>
        private readonly Repository.Utility _unitl;

        /// <summary>
        /// 
        /// </summary>
        public readonly IHostingEnvironment _hostingEnvironment;
        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="config"></param>
        /// <param name="maintenance"></param>
        /// <param name="hostingEnvironment"></param>
        /// <param name="unitl"></param>
        public MaintenanceController(ILogger<MaintenanceController> logger, IConfiguration config, Maintenance maintenance, IHostingEnvironment hostingEnvironment, Repository.Utility unitl)
        {
            _logger = logger;
            _config = config;
            _maintenance = maintenance;
            _hostingEnvironment = hostingEnvironment;
            _unitl = unitl;
        }

        #region GET
        /// <summary>
        /// 获取服务合同列表信息
        /// </summary>
        /// <param name="Area">行政区划(省、市、县)</param>
        /// <param name="CustomerName">客户单位</param>
        /// <param name="ContractId">合同编号</param>
        /// <param name="ContractName">项目名称</param>
        /// <param name="Territory">责任区域 (多选)</param>
        /// <param name="PrimaryTerritory">主跟进组(多选)</param>
        /// <param name="AdvancingState">推进 (多选))</param>
        /// <param name="TrackPepole">跟踪人员)</param>
        /// <param name="ContractDate">计划签订</param>
        /// <param name="ProjectMaturity">成熟度(多选)</param>
        /// <param name="ProjectLevel">跟踪等级(多选)</param>
        /// <param name="ContractDirection"></param>
        /// <param name="SignType">签订类型</param>
        /// <param name="EstimatedAmount">预估金额</param>
        /// <param name="IsAdvancingState">待跟踪</param>
        /// <param name="IsEnable">是否在跟</param>
        /// <param name="PageSize">分页大小</param>
        /// <param name="PageIndex">第几页</param>
        /// <returns></returns>
        [HttpGet("lists")]
        public JsonResult GetContractsLists(string Area,
           string CustomerName,
           string ContractId,
           string ContractName,
           string TrackPepole,
           string ContractDate,
           string SignType,
           string EstimatedAmount,
           string IsAdvancingState,
           string Territory,
           string PrimaryTerritory,
           string AdvancingState,
           string ProjectMaturity,
           string ProjectLevel,
           string ContractDirection,
           string IsEnable,
           int PageSize = 50,
           int PageIndex = 1)
        {
            try
            {
                string[] newTerritory = null,
                    newPrimaryTerritory = null,
                    newAdvancingState = null,
                    newProjectMaturity = null,
                    newContractDirection = null,
                    newProjectLevel = null;

                if (null != Territory) newTerritory = Territory.Split(",");
                if (null != PrimaryTerritory) newPrimaryTerritory = PrimaryTerritory.Split(",");
                if (null != AdvancingState) newAdvancingState = AdvancingState.Split(",");
                if (null != ProjectMaturity) newProjectMaturity = ProjectMaturity.Split(",");
                if (null != ProjectLevel) newProjectLevel = ProjectLevel.Split(",");
                if (null != ContractDirection) newContractDirection = ContractDirection.Split(",");

                var data = _maintenance.GetContractsLists(new
                {
                    Area,
                    CustomerName,
                    ContractId,
                    ContractName,
                    newTerritory,
                    newPrimaryTerritory,
                    newAdvancingState,
                    TrackPepole,
                    ContractDate,
                    newProjectMaturity,
                    newProjectLevel,
                    SignType,
                    EstimatedAmount,
                    IsAdvancingState,
                    newContractDirection,
                    IsEnable,
                    PageSize,
                    PageIndex
                }).OrderBy(d => d.Id);
                
                var newData = data.Where(d => d.Id > ((PageIndex - 1) * PageSize) && d.Id <= PageSize * PageIndex);

                var result = new
                {
                    pageSize = PageSize,
                    pageIndex = PageIndex,
                    totalCount = data.Count(),
                    data = newData
                };
                return Json(result);

            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据合同编号查询项目信息
        /// </summary>
        /// <param name="ContractId">合同编号</param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetContractsByContractId(string ContractId)
        {
            try
            {
                var data = _maintenance.GetContractsByContractId(new { ContractId });
                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据合同编号查询根据记录列表
        /// </summary>
        /// <param name="ContractId">合同编号</param>
        /// <param name="Type">跟进记录类型</param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        [HttpGet("records")]
        public JsonResult GetRecordsByContractId(string ContractId, int Type = 1, int PageSize = 50, int PageIndex = 1)
        {
            try
            {
                var data = _maintenance.GetRecordsByContractId(new { ContractId, Type });

                var newData = data.Where(d => d.RowId > ((PageIndex - 1) * PageSize) && d.RowId <= PageSize * PageIndex);

                var result = new
                {
                    pageSize = PageSize,
                    pageIndex = PageIndex,
                    totalCount = data.Count(),
                    data = newData
                };
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
        /// <summary>
        /// 根据计划月份获取计划项目信息列表
        /// </summary>
        /// <param name="PlanMonth">计划月份</param>
        /// <param name="Territory">责任区域(多选)</param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        [HttpGet("planlists")]
        public JsonResult GetContractsByPlanMonth(string PlanMonth, string Territory, int PageSize = 50, int PageIndex = 1)
        {
            try
            {
                string[] newTerritory = null;
                if (null != Territory) newTerritory = Territory.Split(",");

                var data = _maintenance.GetContractsByPlanMonth(new { PlanMonth, newTerritory });

                var newdData = data.OrderBy(f => f.Id).Where(d => d.Id > (PageIndex - 1) * PageSize && d.Id <= PageSize * PageIndex);

                var result = new
                {
                    pageSize = PageSize,
                    pageIndex = PageIndex,
                    totalCount = data.Count(),
                    data = newdData
                };
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据计划月份获取计划完成情况数据(自签/协签)
        /// </summary>
        /// <param name="PlanMonth">计划月份</param>
        /// <param name="PlanYear">计划年份</param>
        /// <returns></returns>
        [HttpGet("plan")]
        public JsonResult GetPlan2ByPlanMonth(string PlanMonth, string PlanYear)
        {
            try
            {
                List<MaintenancePlan2> data;

                if (null == PlanMonth && null == PlanYear) PlanMonth = DateTime.Now.ToString("yyyy-MM");

                if (null != PlanMonth)
                {
                    data = _maintenance.GetPlan2ByPlanMonth(new { PlanMonth }).ToList();
                }
                else
                {
                    data = _maintenance.GetPlan2ByPlanYear(new { PlanYear }).ToList();
                }

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据计划月份获取计划完成情况数据(大区)
        /// </summary>
        /// <param name="PlanMonth"></param>
        /// <param name="PlanYear"></param>
        /// <returns></returns>
        [HttpGet("plan2")]
        public JsonResult GetPlanByPlanMonth(string PlanMonth, string PlanYear)
        {
            try
            {
                List<MaintenancePlan> data;

                if (null == PlanMonth && null == PlanYear) PlanMonth = DateTime.Now.ToString("yyyy-MM");

                if (null != PlanMonth)
                {
                    data = _maintenance.GetPlanByPlanMonth(new { PlanMonth }).ToList();
                }
                else
                {
                    data = _maintenance.GetPlanByPlanYear(new { PlanYear }).ToList();
                }

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据服务合同编号，验证是否存在
        /// </summary>
        /// <param name="ContractId"></param>
        /// <returns></returns>
        [HttpGet("void")]
        public JsonResult VoidByContractId(string ContractId)
        {
            try
            {
                var data = _maintenance.GetContractsByContractId(new { ContractId }).Count() > 0 ? true : false;
                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 获取逐月服务合同计划与完成情况
        /// </summary>
        /// <param name="Year">年份</param>
        /// <param name="Territory">组别</param>
        /// <returns></returns>
        [HttpGet("distribution")]
        public JsonResult GetDistributionByMonth(string Year, string Territory)
        {
            try
            {
                if (null == Year) Year = DateTime.Now.Year.ToString();

                var data = _maintenance.GetDistributionByMonth(new { Year, Territory });
                decimal SinceDone = 0, AgreementdDone = 0, SincePlan = 0, AgreementdPlan = 0;
                var nowDay = DateTime.Now.ToString("yyyy-MM");

                List<MaintenanceDistributionResult> data2 = new List<MaintenanceDistributionResult>();

                for (var i = 1; i <= 12; i++)
                {

                    MaintenanceDistributionResult result = new MaintenanceDistributionResult();
                    if (i < 10)
                    {
                        result.Month = Year + "-0" + i;
                    }
                    else
                    {
                        result.Month = Year + "-" + i;
                    }
                    
                    result.Since = data.Where(d => d.SignType == "自签" && d.Month == result.Month).Select(a => a.Amount).Sum();
                    result.Agreementd = data.Where(d => d.SignType == "协签" && d.Month == result.Month).Select(a => a.Amount).Sum();

                    // 如果月份小于当前月份，说明该月份项目已完成
                    if (DateTime.Parse(result.Month) < DateTime.Parse(nowDay))
                    {
                        result.IsDone = true;
                        // 自/协签合计
                        SinceDone += result.Since;
                        AgreementdDone += result.Agreementd;
                    }
                    else {
                        SincePlan += result.Since;
                        AgreementdPlan += result.Agreementd;
                    }
                    data2.Add(result);
                }

                var data3 = new
                {
                    SinceDone = SinceDone,
                    AgreementdDone = AgreementdDone,
                    SincePlan = SincePlan,
                    AgreementdPlan = AgreementdPlan,
                    data = data2
                };

                return Json(data3);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 获取各小组签订统计信息
        /// </summary>
        /// <param name="Year"></param>
        /// <returns></returns>
        [HttpGet("territorystats")]
        public JsonResult GetStatsByTerritory(string Year)
        {
            try
            {
                if (null == Year) Year = DateTime.Now.Year.ToString();

                var data = _maintenance.GetStatsSuccess(new { Year });

                List<MaintenanceStatsByTerritoryResult> result = new List<MaintenanceStatsByTerritoryResult>();

                string[] _Territory = {"服务一组", "服务二组", "服务三组","服务四组","服务五组","服务六组","服务七组","运营组","海南分公司"};

                foreach (var iTerritory in _Territory)
                {
                    var _data = data.Where(d => d.Territory == iTerritory);

                    MaintenanceStatsByTerritoryResult _result = new MaintenanceStatsByTerritoryResult();

                    _result.Territory = _data.Select(s => s.Territory).ToArray()[0];
                    // 统计出自签计划额与计划个数
                    _result.SincePlan = _data.Where(d => d.SignType == "自签" && d.ProjectMaturity != "已签").Select(s => s.EstimatedAmount).Sum();
                    _result.SincePlanCount = _data.Where(d => d.SignType == "自签" && d.ProjectMaturity != "已签").Select(s => s.EstimatedAmount).Count();
                    // 统计出协签计划额与计划个数
                    _result.AgreementdPlan = _data.Where(d => d.SignType == "协签" && d.ProjectMaturity != "已签").Select(s => s.EstimatedAmount).Sum();
                    _result.AgreementdPlanCount = _data.Where(d => d.SignType == "协签" && d.ProjectMaturity != "已签").Select(s => s.EstimatedAmount).Count();
                    // 统计出自签完成额与个数
                    _result.SinceDone = _data.Where(d => d.SignType == "自签" && d.ProjectMaturity == "已签").Select(s => s.SignAmount).Sum();
                    _result.SinceDoneCount = _data.Where(d => d.SignType == "自签" && d.ProjectMaturity == "已签").Select(s => s.SignAmount).Count();
                    // 统计出协签完成额与个数
                    _result.AgreementdDone = _data.Where(d => d.SignType == "协签" && d.ProjectMaturity == "已签").Select(s => s.SignAmount).Sum();
                    _result.AgreementdDoneCount = _data.Where(d => d.SignType == "协签" && d.ProjectMaturity == "已签").Select(s => s.SignAmount).Count();

                    result.Add(_result);
                }
                
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 获取各成熟度统计信息
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Territory"></param>
        /// <returns></returns>
        [HttpGet("maturitystats")]
        public JsonResult GetStatsByMaturity(string Year, string Territory)
        {
            try
            {
                if (null == Year) Year = DateTime.Now.Year.ToString();

                var data = _maintenance.GetStatsSuccess(new { Year, Territory });

                List<MaintenanceStatsByMaturityResult> result = new List<MaintenanceStatsByMaturityResult>();

                string[] _Maturity = { "0%", "10%", "20%", "30%", "50%", "80%", "90%", "已签" };

                foreach (var item in _Maturity)
                {
                    MaintenanceStatsByMaturityResult _result = new MaintenanceStatsByMaturityResult();
                    var _data = data.Where(d => d.ProjectMaturity == item);

                    _result.Maturity = item;
                    if (item != "已签")
                    {
                        _result.Since = _data.Where(d => d.SignType == "自签").Select(s => s.EstimatedAmount).Sum();
                        _result.SinceCount = _data.Where(d => d.SignType == "自签").Select(s => s.EstimatedAmount).Count();
                        _result.Agreementd = _data.Where(d => d.SignType != "自签").Select(s => s.EstimatedAmount).Sum();
                        _result.AgreementdCount = _data.Where(d => d.SignType != "自签").Select(s => s.EstimatedAmount).Count();
                    }
                    else
                    {
                        _result.Since = _data.Where(d => d.SignType == "自签").Select(s => s.SignAmount).Sum();
                        _result.SinceCount = _data.Where(d => d.SignType == "自签").Select(s => s.SignAmount).Count();
                        _result.Agreementd = _data.Where(d => d.SignType != "自签").Select(s => s.SignAmount).Sum();
                        _result.AgreementdCount = _data.Where(d => d.SignType != "自签").Select(s => s.SignAmount).Count();
                    }

                    result.Add(_result);
                }

                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 获取各小组逐月完成情况
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        [HttpGet("statsbymonth")]
        public JsonResult GetStatsMonthByMonthDone(string Year, string Type = "type" )
        {
            try
            {
                if (null == Year) Year = DateTime.Now.Year.ToString();

                // 获取数据
                var data = _maintenance.GetStatsSuccess(new { Year, ProjectMaturity="已签" });

                var nowMonth = DateTime.Now.Month;

                if (String.Compare(Year, DateTime.Now.Year.ToString()) == -1)
                {
                    nowMonth = 12;
                }
                else if (String.Compare(Year, DateTime.Now.Year.ToString()) == 1)
                {
                    nowMonth = 1;
                }
                else
                {
                    nowMonth = DateTime.Now.Month;
                }

                string[] _Territory = { "服务一组", "服务二组", "服务三组", "服务四组", "服务五组", "服务六组", "服务七组", "海南分公司" };

                //  返回签订类型统计数据
                if (Type == "type")
                {
                    List<MaintenanceStatsByMonthTypeResult> Result = new List<MaintenanceStatsByMonthTypeResult>();
                    foreach (var item in _Territory)
                    {
                        List<StatsByMonthTypeData> _ListTypeData = new List<StatsByMonthTypeData>();
                        MaintenanceStatsByMonthTypeResult _Result = new MaintenanceStatsByMonthTypeResult();
                        
                        var _data = data.Where(d => d.Territory == item);

                        for (var i = 1; i <= nowMonth; i++)
                        {
                            StatsByMonthTypeData _TypeData = new StatsByMonthTypeData();

                            if (i < 10)
                            {
                                _TypeData.ContractDate = Year + "-0" + i;
                            }
                            else
                            {
                                _TypeData.ContractDate = Year + "-" + i;
                            }
                            _TypeData.SinceDone = _data.Where(d => d.SignType == "自签" && d.ContractDate == _TypeData.ContractDate).Select(s => s.SignAmount).Sum();
                            _TypeData.AgreementDone = _data.Where(d => d.SignType == "协签" && d.ContractDate == _TypeData.ContractDate).Select(s => s.SignAmount).Sum();

                            _ListTypeData.Add(_TypeData);
                        }

                        _Result.Territory = item;
                        _Result.Data = _ListTypeData;

                        Result.Add(_Result);
                    }
                    return Json(Result);
                }
                else
                {
                    List<MaintenanceStatsByMonthAreaResult> Result = new List<MaintenanceStatsByMonthAreaResult>();
                    foreach (var item in _Territory)
                    {
                        
                        List<StatsByMonthAreaData> _ListTypeData = new List<StatsByMonthAreaData>();
                        MaintenanceStatsByMonthAreaResult _Result = new MaintenanceStatsByMonthAreaResult();
                        
                        var _data = data.Where(d => d.Territory == item);

                        for (var i = 1; i <= nowMonth; i++)
                        {
                            StatsByMonthAreaData _TypeData = new StatsByMonthAreaData();

                            if (i < 10)
                            {
                                _TypeData.ContractDate = Year + "-0" + i;
                            }
                            else
                            {
                                _TypeData.ContractDate = Year + "-" + i;
                            }
                            // 小组主跟
                            _TypeData.ResponsibilityDone = _data.Where(d => d.SignType == "自签" && d.ContractDate == _TypeData.ContractDate && d.PrimaryTerritory == d.Territory).Select(s => s.SignAmount).Sum();
                            // 运营主跟
                            _TypeData.OperationDone = _data.Where(d => d.SignType == "自签" && d.ContractDate == _TypeData.ContractDate && d.PrimaryTerritory != d.Territory).Select(s => s.SignAmount).Sum();
                            // 大区主跟
                            _TypeData.AreaDone = _data.Where(d => d.SignType == "协签" && d.ContractDate == _TypeData.ContractDate).Select(s => s.SignAmount).Sum();

                            _ListTypeData.Add(_TypeData);
                        }

                        _Result.Territory = item;
                        _Result.Data = _ListTypeData;

                        Result.Add(_Result);
                    }
                    return Json(Result);
                }
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 获取各小组逐月完成情况2
        /// </summary>
        /// <param name="Year"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        [HttpGet("statsbymonth2")]
        public JsonResult GetStatsMonthByMonthDone2(string Year, string Type = "type")
        {
            try
            {
                if (null == Year) Year = DateTime.Now.Year.ToString();

                // 获取数据
                var data = _maintenance.GetStatsSuccess(new { Year, ProjectMaturity = "已签" });

                var nowMonth = DateTime.Now.Month;

                if (String.Compare(Year, DateTime.Now.Year.ToString()) == -1)
                {
                    nowMonth = 12;
                }
                else if (String.Compare(Year, DateTime.Now.Year.ToString()) == 1)
                {
                    nowMonth = 1;
                }
                else
                {
                    nowMonth = DateTime.Now.Month;
                }
                string[] _Territory = { "服务一组", "服务二组", "服务三组", "服务四组", "服务五组", "服务六组", "服务七组", "海南分公司","合计" };

                //  返回签订类型统计数据
                if (Type == "type")
                {
                    List<MaintenanceStatsByMonthTypeResult2> Result = new List<MaintenanceStatsByMonthTypeResult2>();

                    for (var i = 1; i <= nowMonth; i++)
                    {
                        MaintenanceStatsByMonthTypeResult2 _Result = new MaintenanceStatsByMonthTypeResult2();
                        List<StatsByMonthTypeData2> _ListTypeData = new List<StatsByMonthTypeData2>();
                        
                        if (i < 10)
                        {
                            _Result.ContractDate = Year + "-0" + i;
                        }
                        else
                        {
                            _Result.ContractDate = Year + "-" + i;
                        }

                        var _MonthData = data.Where(f => f.ContractDate == _Result.ContractDate);

                        foreach (var item in _Territory)
                        {
                            var _data = _MonthData.Where(f => f.Territory == item);
                            StatsByMonthTypeData2 _TypeData = new StatsByMonthTypeData2();
                            if (item != "合计")
                            {
                                _TypeData.SinceDone = _data.Where(d => d.SignType == "自签" ).Select(s => s.SignAmount).Sum();
                                _TypeData.AgreementDone = _data.Where(d => d.SignType == "协签").Select(s => s.SignAmount).Sum();
                            }
                            else
                            {
                                _TypeData.SinceDone = _MonthData.Where(d => d.SignType == "自签").Select(s => s.SignAmount).Sum();
                                _TypeData.AgreementDone = _MonthData.Where(d => d.SignType == "协签").Select(s => s.SignAmount).Sum();
                            }
                            _TypeData.Territory = item;
                            _ListTypeData.Add(_TypeData);
                        }
                        _Result.Data = _ListTypeData;

                        Result.Add(_Result);
                    }

                    return Json(Result);
                }
                else
                {
                    List<MaintenanceStatsByMonthAreaResult2> Result = new List<MaintenanceStatsByMonthAreaResult2>();

                    for (var i = 1; i <= nowMonth; i++)
                    {
                        MaintenanceStatsByMonthAreaResult2 _Result = new MaintenanceStatsByMonthAreaResult2();
                        List<StatsByMonthAreaData2> _ListTypeData = new List<StatsByMonthAreaData2>();

                        if (i < 10)
                        {
                            _Result.ContractDate = Year + "-0" + i;
                        }
                        else
                        {
                            _Result.ContractDate = Year + "-" + i;
                        }

                        var _MonthData = data.Where(f => f.ContractDate == _Result.ContractDate);

                        foreach (var item in _Territory)
                        {
                            var _data = _MonthData.Where(f => f.Territory == item);
                            StatsByMonthAreaData2 _AreaData = new StatsByMonthAreaData2();
                            if (item != "合计")
                            {
                                // 小组主跟
                                _AreaData.ResponsibilityDone = _data.Where(d => d.SignType == "自签" && d.PrimaryTerritory == d.Territory).Select(s => s.SignAmount).Sum();
                                // 运营主跟
                                _AreaData.OperationDone = _data.Where(d => d.SignType == "自签" && d.PrimaryTerritory != d.Territory).Select(s => s.SignAmount).Sum();
                                // 大区主跟
                                _AreaData.AreaDone = _data.Where(d => d.SignType == "协签").Select(s => s.SignAmount).Sum();

                            }
                            else
                            {
                                // 小组主跟
                                _AreaData.ResponsibilityDone = _MonthData.Where(d => d.SignType == "自签" && d.PrimaryTerritory == d.Territory).Select(s => s.SignAmount).Sum();
                                // 运营主跟
                                _AreaData.OperationDone = _MonthData.Where(d => d.SignType == "自签" && d.PrimaryTerritory != d.Territory).Select(s => s.SignAmount).Sum();
                                // 大区主跟
                                _AreaData.AreaDone = _MonthData.Where(d => d.SignType == "协签").Select(s => s.SignAmount).Sum();
                            }
                            _AreaData.Territory = item;
                            _ListTypeData.Add(_AreaData);
                        }
                        _Result.Data = _ListTypeData;

                        Result.Add(_Result);
                    }

                    return Json(Result);
                }
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据合同编号获取服务合同计划信息
        /// </summary>
        /// <param name="ContractId"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageIndex"></param>
        /// <returns></returns>
        [HttpGet("planprocess")]
        public JsonResult GetPlanpRocess(string ContractId, int PageSize = 10, int PageIndex = 1)
        {
            try
            {
                var data = _maintenance.GetPlanProcessById(new { ContractId });

                var newdData = data.OrderBy(f => f.rowId).Where(d => d.rowId > (PageIndex - 1) * PageSize && d.rowId <= PageSize * PageIndex);

                var result = new
                {
                    pageSize = PageSize,
                    pageIndex = PageIndex,
                    totalCount = data.Count(),
                    data = newdData
                };
                return Json(result);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 验证项目计划月份是否存在
        /// </summary>
        /// <param name="ContractId"></param>
        /// <param name="PlanMonth"></param>
        /// <returns></returns>
        [HttpGet("voidplanprocess")]
        public JsonResult GetVoidPlanpRocess(string ContractId, string PlanMonth)
        {
            try
            {
                var data = _maintenance.GetPlanProcessById(new { ContractId, PlanMonth }).Count() > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
        #endregion GET

        #region POST

        /// <summary>
        /// 新增/修改服务合同项目信息
        /// </summary>
        /// <param name="maintenance"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult AddMaintenance(MaintenanceContracts maintenance)
        {
            try
            {
                var data = _maintenance.AddMaintenance(maintenance) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 新增服务合同跟进记录
        /// </summary>
        /// <param name="records"></param>
        /// <returns></returns>
        [HttpPost("record")]
        public JsonResult AddRecords([FromBody] MaintenanceRecords records)
        {
            try
            {
                var data = _maintenance.AddRecords(records) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
        /// <summary>
        /// 记录月份签订计划时间
        /// </summary>
        /// <param name="maintenancePlanProcess"></param>
        /// <returns></returns>
        [HttpPost("planprocess")]
        public JsonResult AddPlanProcess([FromBody]MaintenancePlanProcess maintenancePlanProcess)
        {
            try
            {
                var nowDay = DateTime.Now.Day;
                if (nowDay >= 25) maintenancePlanProcess.InserTime = DateTime.Now.ToString("yyyy-MM") + "-25";
                if (nowDay < 3) maintenancePlanProcess.InserTime = DateTime.Now.AddMonths(-1).ToString("yyyy-MM") + "-25";

                //if (null == maintenancePlanProcess.InserTime) return Json(false);

                var data = _maintenance.AddPlanProcess(maintenancePlanProcess) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
        #endregion POST

        #region DELETE

        /// <summary>
        /// 根据合同编号删除服务项目
        /// </summary>
        /// <param name="ContractId"></param>
        /// <returns></returns>
        [HttpDelete]
        public JsonResult DeleteMaintenance(string ContractId)
        {
            try
            {
                var data = _maintenance.DelMaintenance(new { ContractId }) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据记录ID删除跟进记录
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("records")]
        public JsonResult DeleteRecords(string Id)
        {
            try
            {
                var data = _maintenance.DelRecords(new { Id }) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 根据计划记录ID删除月份计划信息
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpDelete("planprocess")]
        public JsonResult DeletePlanProcess(string Id)
        {
            try
            {
                var data = _maintenance.DelPlanProcess(new { Id }) > 0 ? true : false;

                return Json(data);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }
        #endregion DELETE

        #region   数据导出
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Area"></param>
        /// <param name="CustomerName"></param>
        /// <param name="ContractId"></param>
        /// <param name="ContractName"></param>
        /// <param name="TrackPepole"></param>
        /// <param name="ContractDate"></param>
        /// <param name="SignType"></param>
        /// <param name="EstimatedAmount"></param>
        /// <param name="IsAdvancingState"></param>
        /// <param name="Territory"></param>
        /// <param name="PrimaryTerritory"></param>
        /// <param name="AdvancingState"></param>
        /// <param name="ProjectMaturity"></param>
        /// <param name="ProjectLevel"></param>
        /// <param name="IsEnable"></param>
        /// <param name="ContractDirection"></param>
        /// <returns></returns>
        [HttpGet("exprot")]
        public JsonResult GetContractsExprot(string Area,
           string CustomerName,
           string ContractName,
           string TrackPepole,
           string ContractDate,
           string SignType,
           string EstimatedAmount,
           string IsAdvancingState,
           string Territory,
           string PrimaryTerritory,
           string AdvancingState,
           string ProjectMaturity,
           string ProjectLevel,
            string IsEnable,
           string ContractDirection,
           string ContractId)
        {
            try
            {
                string[] newTerritory = null,
                    newPrimaryTerritory = null,
                    newAdvancingState = null,
                    newProjectMaturity = null,
                    newContractDirection = null,
                    newProjectLevel = null;

                if (null != Territory) newTerritory = Territory.Split(",");
                if (null != PrimaryTerritory) newPrimaryTerritory = PrimaryTerritory.Split(",");
                if (null != AdvancingState) newAdvancingState = AdvancingState.Split(",");
                if (null != ProjectMaturity) newProjectMaturity = ProjectMaturity.Split(",");
                if (null != ProjectLevel) newProjectLevel = ProjectLevel.Split(",");
                if (null != ContractDirection) newContractDirection = ContractDirection.Split(",");

                var data = _maintenance.GetContractsLists(new
                {
                    Area,
                    CustomerName,
                    ContractId,
                    ContractName,
                    newTerritory,
                    newPrimaryTerritory,
                    newAdvancingState,
                    TrackPepole,
                    ContractDate,
                    newProjectMaturity,
                    newProjectLevel,
                    SignType,
                    IsEnable,
                    EstimatedAmount,
                    newContractDirection,
                    IsAdvancingState
                }).OrderBy(d => d.Id);

                JToken titleConfig = JToken.Parse("['责任区域','省份','市','县','客户单位','项目名称','原合同编号','新合同编号','推进','主跟小组','分布','成熟度','是否预算','预算金额','预估金额','跟踪等级','计划签订','主跟进人','跟进时间','跟踪情况','类型方向','签订类型','签订金额','签订人员','失败原因','是否备案','到期时间','备注','新增时间']");

                JToken fieldConfig = JToken.Parse("['Territory','Province','City','County','CustomerName','ContractName','ContractId','NewContractId','AdvancingState','PrimaryTerritory','ContractType','ProjectMaturity','IsBudget','BudgetAmount','EstimatedAmount','ProjectLevel','ContractDate','TrackPepole','Tm','Content','ContractDirection','SignType','SignAmount','ContractingOfficer','CauseFailure','IsReport','EndTime','Remark','InsertTime']");

                List<string> tempList = new List<string>();

                data.ForEach(e =>
                {
                    tempList.Add("{Territory:'" + e.Territory + "',Province:'" + e.Province + "',City:'" + e.City + "',County:'" + e.County + "',CustomerName:'" + e.CustomerName +"',ContractName:'" + e.ContractName + "',ContractId:'" + e.ContractId + "',NewContractId:'" + e.NewContractId + "',AdvancingState:'" + e.AdvancingState + "',PrimaryTerritory:'" + e.PrimaryTerritory + "',ContractType:'" + e.ContractType + "',ProjectMaturity:'" + e.ProjectMaturity + "',IsBudget:'" + e.IsBudget + "',BudgetAmount:'" + e.BudgetAmount + "',EstimatedAmount:'" + e.EstimatedAmount + "',ProjectLevel:'" + e.ProjectLevel + "',ContractDate:'" + e.ContractDate + "',TrackPepole:'" + e.TrackPepole + "',Tm:'" + e.Tm + "',Content:'" + e.Content + "',ContractDirection:'" + e.ContractDirection + "',SignType:'" + e.SignType + "',SignAmount:'" + e.SignAmount + "',ContractingOfficer:'" + e.ContractingOfficer + "',CauseFailure:'" + e.CauseFailure + "',IsReport:'" + e.IsReport + "',EndTime:'" + e.EndTime + "',Remark:'" + e.Remark + "',InsertTime:'" + e.InsertTime + "'}");
                });
                JToken exportData = JToken.Parse("[" + string.Join(",", tempList) + "]");
                string resultPath = _unitl.ExportCustomerToExcel(titleConfig, fieldConfig, exportData, "服务合同盘点表_");
                var rootUrl = HttpContext.Request.Host.Value + "/Results";

                resultPath = resultPath.Replace(_hostingEnvironment.ContentRootPath, "").ToHttpStylePath();

                var resultUrl = string.Format("{0}{1}", rootUrl, resultPath);

                return Json(resultUrl);

            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        /// <summary>
        /// 导出服务合同计划表
        /// </summary>
        /// <param name="PlanMonth"></param>
        /// <param name="PlanYear"></param>
        /// <param name="Type"></param>
        /// <returns></returns>
        [HttpGet("exprotplan")]
        public JsonResult GetPlanByPlanMonthExprot(string PlanMonth, string PlanYear, string Type = "type")
        {
            try
            {
                if (null == PlanMonth && null == PlanYear) PlanMonth = DateTime.Now.ToString("yyyy-MM");
                List<string> tempList = new List<string>();

                JToken titleConfig;
                JToken fieldConfig;
                
                if (Type == "type")
                {
                    List<MaintenancePlan2> data = new List<MaintenancePlan2>();
                   if (null != PlanMonth)
                    {
                        data = _maintenance.GetPlan2ByPlanMonth(new { PlanMonth }).ToList();
                    }
                    else
                    {
                        data = _maintenance.GetPlan2ByPlanYear(new { PlanYear }).ToList();
                    }
                    titleConfig = JToken.Parse("['责任区域','目标业绩','自签目标','协签目标','总业绩','自签完成','协签完成','总完成率','自签完成率','协签完成率']");

                    fieldConfig = JToken.Parse("['Territory','Summation','SinceSigning','AgreementSigned','SummationDone','SinceDone','AgreementDone','SummationPercentage','SincePercentage','AgreementdPercentage']");

                    data.ForEach(e =>
                    {
                        tempList.Add("{Territory:'" + e.Territory + "',Summation:'" + e.Summation + "',SinceSigning:'" + e.SinceSigning + "',AgreementSigned:'" + e.AgreementSigned + "',SummationDone:'" + e.SummationDone + "',SinceDone:'" + e.SinceDone + "',AgreementDone:'" + e.AgreementDone + "',SummationPercentage:'" + e.SummationPercentage + "',SincePercentage:'" + e.SincePercentage + "',AgreementdPercentage:'" + e.AgreementdPercentage + "'}");
                    });
                }
                else
                {
                    List<MaintenancePlan> data = new List<MaintenancePlan>();

                    if (null != PlanMonth)
                    {
                        data = _maintenance.GetPlanByPlanMonth(new { PlanMonth }).ToList();
                    }
                    else
                    {
                        data = _maintenance.GetPlanByPlanYear(new { PlanYear }).ToList();
                    }

                   titleConfig = JToken.Parse("['责任区域','区域目标','小组跟进','运营主跟','大区主跟','区域目标完成','小组完成','运营完成','大区完成','总完成率','小组完成率','运营完成率','大区完成率']");

                   fieldConfig = JToken.Parse("['Territory','Summation','ResponsibilityTarget','OperationTarget','AreaTarget','SummationDone','ResponsibilityDone','OperationDone','AreaDone','SummationPercentage','ResponsibilityPercentage','OperationPercentage','AreaPercentage']");

                    data.ForEach(e =>
                    {
                        tempList.Add("{Territory:'" + e.Territory + "',Summation:'" + e.Summation + "',ResponsibilityTarget:'" + e.ResponsibilityTarget + "',OperationTarget:'" + e.OperationTarget + "',AreaTarget:'" + e.AreaTarget + "',SummationDone:'" + e.SummationDone + "',ResponsibilityDone:'" + e.ResponsibilityDone + "',OperationDone:'" + e.OperationDone + "',AreaDone:'" + e.AreaDone + "',SummationPercentage:'" + e.SummationPercentage + "',ResponsibilityPercentage:'" + e.ResponsibilityPercentage + "',OperationPercentage:'" + e.OperationPercentage + "',AreaPercentage:'" + e.AreaPercentage + "'}");
                    });
                }

                JToken exportData = JToken.Parse("[" + string.Join(",", tempList) + "]");
                string resultPath = _unitl.ExportCustomerToExcel(titleConfig, fieldConfig, exportData, "服务合同盘点计划表_");
                var rootUrl = HttpContext.Request.Host.Value + "/Results";

                resultPath = resultPath.Replace(_hostingEnvironment.ContentRootPath, "").ToHttpStylePath();

                var resultUrl = string.Format("{0}{1}", rootUrl, resultPath);

                return Json(resultUrl);
            }
            catch (Exception ex)
            {
                return Json(ex);
            }
        }

        #endregion  数据导出
    }
}